<?php
/**
 * Created by PhpStorm.
 * User: jocky
 * Date: 30/08/2017
 * Time: 22:08
 */
namespace frontend\models;

use common\models\ar\User;
use common\models\UserTradeIdentity;
use yii\base\Model;

class LoginForm extends Model
{
    public $captchaFlag = true;//必须检测验证码，当用户注册成功后主动登录账户时不是必须
    public $username;
    public $password;
    public $captcha;
    private $_user;


    /**
     * @inheritdoc
     */
    public function rules()
    {
        $rules = [
            ['username', 'required', 'message' => '客户编号不能为空'],
            ['password', 'required', 'message' => '密码不能为空'],

        ];
        if ($this->captchaFlag) {
            $rules[] = ['captcha', 'required', 'message' => '验证码不能为空'];
            $rules[] = ['captcha', 'captcha', 'captchaAction' => 'login/captcha', 'message' => '验证码不正确'];
            $rules[] = ['password', 'validatePassword'];
        }
        return $rules;
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
            if (!$user) {
                $this->addError($attribute, '账号或密码不正确');
                return;
            }

            if ($user->loginpsw != $this->password)
            {
                $this->addError($attribute, '账号或密码不正确');
                return;
            }
        }
    }

    /**
     * Logs in a user using the provided username and password.
     *
     * @return bool whether the user is logged in successfully
     */
    public function login()
    {
        if (!$this->hasErrors()) {
            return \Yii::$app->user->login($this->getUser());
        } else {
            return false;
        }
    }

    /**
     * @return \common\models\UserTradeIdentity|array|null|\yii\db\ActiveRecord
     */
    protected function getUser()
    {
        if ($this->_user === null) {
            $sql = "SELECT 
                      `userID` 
                    FROM 
                      `user` 
                    WHERE 
                      `loginName` = :username";
            $obj = User::findBySql($sql, [':username' => $this->username])->one();
            if ($obj) {
                $this->_user = UserTradeIdentity::findIdentity($obj->userID);
            }
        }

        return $this->_user;
    }
}